// 命令行参数： 表名、是否需要权限、是否开启Cache
import fs from 'fs'
import { PrismaClient } from '../../../prisma/generated/uctoo';
const args = process.argv.slice(2); // 去掉数组中的前两个元素
// 打印命令行参数
console.log('命令行参数:', args);
if (!args.length) {
  console.error('参数错误')
  process.exit(0)
}

let tableName = args[0]
// 首字母小写
let lowerTableName = convertToCamelCase(tableName)
// 首字母大写
const upperTableName = `${lowerTableName.charAt(0).toLocaleUpperCase()}${lowerTableName.slice(1)}`
// 首字母小写
// const tableName = `${inputTableName.charAt(0).toLocaleLowerCase()}${inputTableName.slice(1)}`
const requireUser = args[1] ? args[1] : 'false'
const cache = args[2] ? args[2] : 'false'
//console.log('tableName:' + tableName)
//console.log('tableNameFirst:' + tableNameFirst)

const autoCodeStartStr = "//#region AutoCreateCode"
const autoCodeEndStr = "//#endregion AutoCreateCode"
const path = process.cwd()
const config = {
  service: {
    tpl: `${path}/src/app/services/entity.ts.tpl`,
    target: `${path}/src/app/services`,
    name: `${tableName}.ts`
  },
  controller: {
    tpl: `${path}/src/app/controllers/entity/index.ts.tpl`,
    target: `${path}/src/app/controllers/${tableName}`,
    name: `index.ts`
  },
  route: {
    tpl: `${path}/src/app/routes/entity/index.ts.tpl`,
    target: `${path}/src/app/routes/${tableName}`,
    name: `index.ts`
  }
} 
        createModule("service", config, tableName, lowerTableName, upperTableName, requireUser, cache)
        createModule("controller", config, tableName, lowerTableName, upperTableName, requireUser, cache)
        createModule("route", config, tableName, lowerTableName, upperTableName, requireUser, cache)
        appendControllers(path, tableName, lowerTableName, upperTableName,)
        appendRoutes(path, tableName, lowerTableName, upperTableName,)

function convertToCamelCase(str) {
  return str.toLowerCase().replace(/_(.)/g, function (match, group1) {
    return group1.toUpperCase();
  });
}
function createModule(module, config, tableName, lowerTableName, upperTableName, requestUser, cache) {
  const replaceFun = {
    service: replaceService,
    controller: replaceController,
    route: replaceRouter,
  }
  const autoCodeStartStr = "//#region AutoCreateCode"
  const autoCodeEndStr = "//#endregion AutoCreateCode"
  const tplPath = config[module].tpl
  const targetPath = config[module].target
  const targetName = config[module].name
  const targetFullName = `${targetPath}/${targetName}`
  if (!fs.existsSync(targetPath)) {
    try {
      fs.mkdirSync(targetPath, { recursive: true });
    } catch (err) {
      console.error(err);
    }
  }
  let tplData = ''
  try {
    const data = fs.readFileSync(tplPath, 'utf8');
    // console.log(data);
    if (data) {
      tplData = replaceFun[module](data, tableName, lowerTableName, upperTableName, requestUser, cache)
      if (tplData) {
        console.log("fs.existsSync(targetFullName):", fs.existsSync(targetFullName))
        if (fs.existsSync(targetFullName)) {
          const targetData = fs.readFileSync(`${targetFullName}`, 'utf8');
          const targetStart = targetData.indexOf(autoCodeStartStr)
          if (targetStart <= -1) {
            console.log(`targetPath cant not match ${autoCodeStartStr}!${targetFullName}`)
            return
          }
          const targetEnd = targetData.indexOf(autoCodeEndStr)
          if (targetEnd <= -1) {
            console.log(`targetPath cant not match ${autoCodeEndStr}!`)
            return
          }
          if (targetStart >= targetEnd) {
            console.log(`targetPath start>=end,please check!start=${targetStart}, end =${targetEnd} `)
            return
          }
          const headStr = targetData.slice(0, targetStart)
          const footStr = targetData.slice(targetEnd, targetData.length)
          //拆分
          const tplStart = tplData.indexOf(autoCodeStartStr)
          if (tplStart <= -1) {
            console.log(`tplPath cant not match ${autoCodeStartStr}!`)
            return
          }
          const tplEnd = tplData.indexOf(autoCodeEndStr)
          if (tplEnd <= -1) {
            console.log(`tplPath cant not match ${autoCodeEndStr}!`)
            return
          }
          if (tplStart >= tplEnd) {
            console.log(`tplPath start>=end,please check!start=${tplStart}, end =${tplEnd} `)
            return
          }
          const middleStr = tplData.slice(tplStart, tplEnd)
          tplData = `${headStr}${middleStr}${footStr}`
          console.log(tplStart, tplEnd, targetStart, targetEnd)
        }
        console.log('tplData length:', tplData.length)
        fs.writeFileSync(`${targetFullName}`, tplData)
        console.log(`writeFile ${targetFullName} success!`)
      } else {
        console.log(`writeFile ${targetFullName} error! no context`)
      }
    }
  } catch (err) {
    console.error('处理文件出错', err);
  }
}

function replaceService(data, tableName, lowerTableName, upperTableName, requireUser, cache) {
  const context = data.replace(/Entity/g, upperTableName).replace(/entity/g, lowerTableName).replace(/table_name/g, tableName)
  return context
}
function replaceController(data, tableName, lowerTableName, upperTableName, requireUser, cache) {
  const context = data.replace(/Entity/g, upperTableName)
    .replace(/entity/g, lowerTableName)
    // .replace(`} from '../../services/table_name';`, `count${upperTableName}s\r\n} from '../../services/table_name';`)
    .replace(/table_name/g, tableName)
  return context
}
function replaceRouter(data, tableName, lowerTableName, upperTableName, requireUser, cache) {
  let context = data.replace(/Entity/g, upperTableName).replace(/entity/g, lowerTableName)
  if (requireUser == 'true') {
    context = context.replace(/needRequireUser,/g, 'requireUser,')
  } else {
    context = context.replace(/needRequireUser,/g, "")
  }
  if (cache == 'true') {
    context = context.replace(/needCache,/g, 'cache,')
  } else {
    context = context.replace(/needCache,/g, "")
  }
  return context
}

function appendControllers(path, tableName, lowerTableName, upperTableName,) {
  const tplPath = `${path}/src/app/controllers/index.ts`
  const targetPath = `${path}/src/app/controllers`
  // 判断是否有目录，没有要创建
  if (!fs.existsSync(targetPath)) {
    try {
      fs.mkdirSync(targetPath, { recursive: true });
    } catch (err) {
      console.error(err);
    }
  }
  let context = ''
  try {
    const data = fs.readFileSync(tplPath, 'utf8');
    if (data) {
      context = data
      if (data.indexOf(`${upperTableName}Controller from`) < 0) {
        context = data.replace('export {', `import ${upperTableName}Controller from './${tableName}';\r\nexport {`)
          .replace('};', `  ${upperTableName}Controller,\r\n};`)
      }
      if (context) {
        fs.writeFileSync(`${targetPath}/index.ts`, context)
        console.log(`writeFile ${targetPath}/index.ts success!`)
      } else {
        console.log(`writeFile ${targetPath}/index.ts error! no context`)
      }
    }
  } catch (err) {
    console.error('处理文件出错', err);
  }
}
function appendRoutes(path, tableName, lowerTableName, upperTableName,) {
  const tplPath = `${path}/src/app/routes/index.ts`
  const targetPath = `${path}/src/app/routes`
  // 判断是否有目录，没有要创建
  if (!fs.existsSync(targetPath)) {
    try {
      fs.mkdirSync(targetPath, { recursive: true });
    } catch (err) {
      console.error(err);
    }
  }
  let context = ''
  try {
    const data = fs.readFileSync(tplPath, 'utf8');
    if (data) {
      context = data
      if (data.indexOf(`/${tableName}`) < 0) {
        context = data.replace(/const api_router = new Router/g, `import ${lowerTableName}Router from './${tableName}';\r\nconst api_router = new Router`)
          .replace(/export default api_router/g, `api_router.use('/${tableName}', ${lowerTableName}Router);\r\nexport default api_router`)
      }
      if (context) {
        fs.writeFileSync(`${targetPath}/index.ts`, context)
        console.log(`writeFile ${targetPath}/index.ts success!`)
      } else {
        console.log(`writeFile ${targetPath}/index.ts error! no context`)
      }
    }
  } catch (err) {
    console.error('处理文件出错', err);
  }
}
